//
//  HomeTableViewCell.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/19.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "HomeTableViewCell.h"
#import "XHStarRateView.h"
#import <CoreLocation/CoreLocation.h>

@interface HomeTableViewCell ()

@property (nonatomic, weak)UIView * backImageView;
@property (nonatomic, weak)UIImageView * iconImageView;
@property (nonatomic, weak)UILabel * titleLabel;
@property (nonatomic, weak)XHStarRateView * starView;
@property (nonatomic, strong)UILabel * distanceLabel;
@property (nonatomic, strong)UILabel * commentLabel;
@property (nonatomic, strong)UILabel * soldLabel;
@property (nonatomic, strong)UILabel * dateLabel;
@property (nonatomic, strong)UILabel * shopLabel;
@property (nonatomic, weak)UILabel * priceLabel;
@property (nonatomic, weak)UILabel * orPriceLabel;
@property (nonatomic, weak)UIView * smallView;
@property (nonatomic, weak)UIImageView * tuanImageView;



@end


@implementation HomeTableViewCell


- (void)setModel:(GoodsModel *)model{
    
    _model = model;
    
    self.titleLabel.text = model.merchants_goods_name;
    int count = [model.merchants_goods_comments_star_level intValue];
    if (count == 0) {
        self.starView.width = 1 * SCREENH6;;
    }else{
       self.starView.currentRating = count;
    }
    
    NSArray *array = [model.merchants_goods_img componentsSeparatedByString:@","];
    NSString * img = array.firstObject;
    NSString * usrlStr = [NSString stringWithFormat:@"%@%@",BASEURLSTR,img];
    NSURL * url = [NSURL URLWithString:usrlStr];
    [self.iconImageView sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"组12"]];
    self.commentLabel.text = [NSString stringWithFormat:@"%@评论",model.merchants_goods_comments_number];
    self.shopLabel.text = model.merchants_name;
    self.priceLabel.text = [NSString stringWithFormat:@"￥%@",model.merchatns_goods_platform_discount_price];
//    self.orPriceLabel.text = [NSString stringWithFormat:@"原价 ￥%@",model.merchants_goods_price];
    NSString * orString = [NSString stringWithFormat:@"￥%@",model.merchatns_goods_platform_price];
    //中划线
    NSDictionary *attribtDic = @{NSStrikethroughStyleAttributeName: [NSNumber numberWithInteger:NSUnderlineStyleSingle]};
    NSMutableAttributedString *attribtStr = [[NSMutableAttributedString alloc]initWithString:orString attributes:attribtDic];
    
    self.orPriceLabel.attributedText = attribtStr;
    
    self.soldLabel.text = [NSString stringWithFormat:@"已售%@",model.merchants_goods_sold];
    
    double userLat = [DEF_GET_OBJECT(@"lat") doubleValue];
    double userLon = [DEF_GET_OBJECT(@"lon") doubleValue];
    
    if (userLat && userLon) {
        
        double lat = [model.merchants_latitude doubleValue];
        double lon = [model.merchants_longitude doubleValue];
        
        double res = [self distanceBetweenOrderBy:lat :userLat :lon :userLon];
        if (res > 1000) {
            
            res = res / 1000;
            self.distanceLabel.text = [NSString stringWithFormat:@"%.2fkm",res];
        }else{
            
            self.distanceLabel.text = [NSString stringWithFormat:@"%.2fm",res];
        }
    }else{
        
        self.distanceLabel.hidden = YES;
    }
   
    int is_official = [model.is_official intValue];
    
    if (is_official == 0) {
        
        int merchants_goods_type = [model.merchants_goods_type intValue];
        if (merchants_goods_type == 1) {
            
            self.tuanImageView.hidden = YES;
            self.tuanImageView.width = 0;
            self.dateLabel.text = [NSString stringWithFormat:@"%@",model.merchants_goods_available_time];
        }else{
            
            self.tuanImageView.hidden = NO;
            self.tuanImageView.width = 35 * SCREENH6;
            NSDictionary * dict = [self dictionaryWithJsonString:model.merchants_goods_available_time];
            
            NSArray *keysArray = [dict allKeys];
            NSMutableArray * keyMuArr = [NSMutableArray array];
            for (NSString * week in keysArray) {
                
                int w = [week intValue];
                [keyMuArr addObject:@(w)];
            }
            NSArray * weekArr = [self arraySortBreakWith:keyMuArr.copy];
            //        NSLog(@"keyMuArr===%@",keyMuArr);
            NSMutableArray * resMuArr = [NSMutableArray array];
            for (NSString * week in weekArr) {
                
                int w = [week intValue];
                NSString * d = [self isEqualWeekWith:w];
                
                [resMuArr addObject:d];
            }
            
            NSString * res = [resMuArr.copy componentsJoinedByString:@","];
            
            NSString * key = keysArray.firstObject;
            NSArray * value = dict[key];
            NSString *string = [value componentsJoinedByString:@","];
            
            self.dateLabel.text = [NSString stringWithFormat:@"%@ %@",res,string];
        }
    }else{
        
        self.tuanImageView.hidden = NO;
        self.tuanImageView.image = [UIImage imageNamed:@"官方活动标识"];
        self.tuanImageView.width = 35 * SCREENH6;
//        NSDictionary * dict = [self dictionaryWithJsonString:model.merchants_goods_available_time];
//
//        NSArray *keysArray = [dict allKeys];
//        NSMutableArray * keyMuArr = [NSMutableArray array];
//        for (NSString * week in keysArray) {
//
//            int w = [week intValue];
//            [keyMuArr addObject:@(w)];
//        }
//        NSArray * weekArr = [self arraySortBreakWith:keyMuArr.copy];
//        //        NSLog(@"keyMuArr===%@",keyMuArr);
//        NSMutableArray * resMuArr = [NSMutableArray array];
//        for (NSString * week in weekArr) {
//
//            int w = [week intValue];
//            NSString * d = [self isEqualWeekWith:w];
//
//            [resMuArr addObject:d];
//        }
//
//        NSString * res = [resMuArr.copy componentsJoinedByString:@","];
//
//        NSString * key = keysArray.firstObject;
//        NSArray * value = dict[key];
//        NSString *string = [value componentsJoinedByString:@","];
        
        self.dateLabel.text = [NSString stringWithFormat:@"%@",model.merchants_goods_field_time];
    }
    
    
}


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    
    if ([super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        [self setupUI];
    }
    
    return self;
}

- (void)setupUI{
    
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor = ColorWithRGB(0xF8F9FA);
    
    UIImageView * backImageView = [UIImageView new];
    
    backImageView.image = [UIImage imageNamed:@"RoundedRectangle"];
    self.backImageView = backImageView;
    
    [self.contentView addSubview:self.backImageView];
    
    UIImageView * iconImageView = [UIImageView new];
    
//    iconImageView.image = IMAGENAME(@"RoundedRectangle");
    iconImageView.backgroundColor = ZRWhiteColor;
    iconImageView.contentMode = UIViewContentModeScaleAspectFit;
    self.iconImageView = iconImageView;
    
    [self.contentView addSubview:self.iconImageView];
    
    
    UILabel * titleLabel = [UILabel new];
    
    titleLabel.textColor = ZRBlackColor;
    titleLabel.text = @"沙拉轻食包";
    titleLabel.font = [UIFont boldSystemFontOfSize:14 * SCREENH6];
    
    self.titleLabel = titleLabel;
    
    [self.contentView addSubview:self.titleLabel];
    
    self.distanceLabel = [self setupLabelWithTitle:@"760m" WithType:@"gray"];
    [self.contentView addSubview:self.distanceLabel];
    
    XHStarRateView *starRateView = [[XHStarRateView alloc] initWithFrame:CGRectMake(120 * SCREENH6, 30 * SCREENH6, 70 * SCREENH6, 10 * SCREENH6)];
    starRateView.isAnimation = YES; // 有动画
    starRateView.rateStyle = XHStarRateViewRateStyeFullStar; //允许不完整星评论
//    starRateView.delegate = self;
    starRateView.currentRating = 5;
    starRateView.userInteractionEnabled = NO;
    
    self.starView = starRateView;
    [self.contentView addSubview:self.starView];
    
    self.commentLabel = [self setupLabelWithTitle:@"13评论" WithType:@"gray"];
    [self.contentView addSubview:self.commentLabel];
    self.shopLabel = [self setupLabelWithTitle:@"Slim 餐厅" WithType:@"black"];
    [self.contentView addSubview:self.shopLabel];
    self.dateLabel = [self setupLabelWithTitle:@"11 九月 - 21 九月" WithType:@"black"];
    [self.contentView addSubview:self.dateLabel];
    
    UIView * smallView = [UIView new];
    
    smallView.backgroundColor = ColorWithRGB(0xFFE055);
    
    self.smallView = smallView;
    [self.contentView addSubview:self.smallView];
    
    UILabel * priceLabel = [UILabel new];
    
    priceLabel.text = @"$ 19.9";
    priceLabel.textColor = ZRBlackColor;
    priceLabel.font = [UIFont boldSystemFontOfSize:13 * SCREENH6];
    
    self.priceLabel = priceLabel;
    
    [self.contentView addSubview:self.priceLabel];
    
    
    UILabel * orPriceLabel = [UILabel new];
    
    orPriceLabel.text = @"原价 $39.9";
    orPriceLabel.textColor = ZRBlackColor;
    orPriceLabel.font = [UIFont systemFontOfSize:11 * SCREENH6];
    
    self.orPriceLabel = orPriceLabel;
    
    [self.contentView addSubview:self.orPriceLabel];
    
    self.soldLabel = [self setupLabelWithTitle:@"已售23" WithType:@"gray"];
    [self.contentView addSubview:self.soldLabel];
    
    
    UIImageView * tuanImageView = [[UIImageView alloc] initWithFrame:CGRectMake(107 * SCREENH6, 10 * SCREENH6, 35 * SCREENH6, 15 * SCREENH6)];
    
    tuanImageView.image = [UIImage imageNamed:@"拼团商品标识"];
    tuanImageView.hidden = YES;
    
    self.tuanImageView = tuanImageView;
    
    [self.backImageView addSubview:self.tuanImageView];
}


- (void)layoutSubviews{
    
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.contentView).offset(15 * SCREENH6);
        make.trailing.mas_equalTo(self.contentView).offset(-15 * SCREENH6);
        make.top.bottom.mas_equalTo(self.contentView);
    }];
    
    [self.iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.backImageView).offset(12 * SCREENH6);
        make.centerY.mas_equalTo(self.contentView);
        make.width.height.mas_equalTo(85 * SCREENH6);
    }];
    
//    [self.tuanImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.leading.mas_equalTo(self.iconImageView.mas_trailing).offset(10 * SCREENH6);
//        make.top.mas_equalTo(self.backImageView).offset(10 * SCREENH6);
//        make.width.mas_equalTo(35 * SCREENH6);
//        make.height.mas_equalTo(15 * SCREENH6);
//    }];
    
    [self.distanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.tuanImageView);
        make.trailing.mas_equalTo(self.backImageView).offset(-10 * SCREENH6);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.tuanImageView);
        make.trailing.mas_equalTo(self.distanceLabel.mas_leading).offset(-5 * SCREENH6);
        make.leading.mas_equalTo(self.tuanImageView.mas_trailing).offset(3 * SCREENH6);
    }];

    [self.commentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.starView.mas_trailing).offset(10 * SCREENH6);
        make.centerY.mas_equalTo(self.starView);
    }];
    
    [self.shopLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.starView);
        make.trailing.mas_equalTo(self.distanceLabel.mas_leading).offset(-5 * SCREENH6);
        make.top.mas_equalTo(self.starView.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.dateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.shopLabel);
        make.trailing.mas_equalTo(self.distanceLabel.mas_leading).offset(-5 * SCREENH6);
        make.top.mas_equalTo(self.shopLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.smallView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.iconImageView.mas_trailing).offset(18 * SCREENH6);
        make.top.mas_equalTo(self.dateLabel.mas_bottom).offset(7 * SCREENH6);
        make.height.mas_equalTo(14 * SCREENH6);
        make.width.mas_equalTo(32 * SCREENH6);
    }];
    
    [self.priceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.dateLabel);
        make.top.mas_equalTo(self.dateLabel.mas_bottom).offset(5 * SCREENH6);
    }];
    
    [self.orPriceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.priceLabel.mas_trailing).offset(5 * SCREENH6);
        make.centerY.mas_equalTo(self.smallView);
    }];
    
    [self.soldLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.orPriceLabel);
        make.trailing.mas_equalTo(self.distanceLabel);
    }];
}


- (NSString *)isEqualWeekWith:(int)week{
    
    NSString * weekDay;
    switch (week) {
        case 1:
            weekDay = @"周一";
            break;
        case 2:
            weekDay = @"周二";
            break;
        case 3:
            weekDay = @"周三";
            break;
        case 4:
            weekDay = @"周四";
            break;
        case 5:
            weekDay = @"周五";
            break;
        case 6:
            weekDay = @"周六";
            break;
        case 7:
            weekDay = @"周日";
            break;
        default:
            break;
    }
    
    return weekDay;
}


#pragma mark -- 数组排序方法（乱序）
- (NSArray *)arraySortBreakWith:(NSArray *)array{
    
    //对数组进行排序
    NSArray *result = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        
        return [obj1 compare:obj2]; //升序
        
    }];
    
    return result;
    
}


-(double)distanceBetweenOrderBy:(double) lat1 :(double) lat2 :(double) lng1 :(double) lng2{
    
    CLLocation *curLocation = [[CLLocation alloc] initWithLatitude:lat1 longitude:lng1];
    
    CLLocation *otherLocation = [[CLLocation alloc] initWithLatitude:lat2 longitude:lng2];
    
    double  distance  = [curLocation distanceFromLocation:otherLocation];
    
    return  distance;
    
}
- (UILabel *)setupLabelWithTitle:(NSString *)title WithType:(NSString *)type{
    
    UILabel * label = [UILabel new];
    
    label.text = title;
    label.font = [UIFont systemFontOfSize:13 * SCREENH6];
    
    if ([type isEqualToString:@"black"]) {
        
        label.textColor = ZRBlackColor;
    }else if ([type isEqualToString:@"gray"]){
        
        label.textColor = ColorWithRGB(0x909090);
    }
    
    return label;
}


- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
